<?php
// $Id: PopnupBlogUtils.php,v 2.10.3 2005/08/02 21:24:00 yoshis Exp $
$incpath = XOOPS_ROOT_PATH."/modules/popnupblog/";
if(
	!defined('XOOPS_ROOT_PATH') ||
	!defined('XOOPS_CACHE_PATH') ||
	!is_file($incpath.'conf.php') ||
	!is_file($incpath.'pop.ini.php') ||
	!is_file($incpath.'class/PopnupBlogPing2.php') 
){
	exit();
}
include_once $incpath.'pop.ini.php';
include_once $incpath.'conf.php';
include_once $incpath.'class/PopnupBlogPing2.php';
require_once(XOOPS_ROOT_PATH.'/mainfile.php');
class PopnupBlogUtils {
	function log($str){
		if( /* defined(POPNUPBLOG_DEBUG_OUT)  && */ (POPNUPBLOG_DEBUG_OUT == 1) ){
			$postlog = './log/popnupblog.log';
			$fp = fopen($postlog, 'a');
			fwrite($fp, $str."\n");
			fclose($fp);
		}
	}
	
	function getStartFromHttpParams(){
		global $HTTP_POST_VARS, $HTTP_GET_VARS, $xoopsUser;
		
		$start = isset($HTTP_POST_VARS['start']) ? ($HTTP_POST_VARS['start']) : 0;
		if($start == 0){
			$start = isset($HTTP_GET_VARS['start']) ? ($HTTP_GET_VARS['start']) : 0;
		}
		return $start;
	}
	function getDateFromHttpParams(){
		global $_SERVER,$HTTP_POST_VARS, $HTTP_GET_VARS, $xoopsUser;
//echo("<br>_SERVER:"); print_r($_SERVER['PATH_INFO']);
//echo("<br>HTTP_POST_VARS:"); print_r($HTTP_POST_VARS['param']);
//echo("<br>HTTP_GET_VARS:"); print_r($HTTP_GET_VARS['param']);
		$param = isset($HTTP_POST_VARS['param']) ? ($HTTP_POST_VARS['param']) : 0;
		if(!$param){
			if ( isset($HTTP_GET_VARS['param']) ){
				$param = $HTTP_GET_VARS['param'];
		    } elseif ( isset($_SERVER['PATH_INFO']) ){
    	    	$pa = explode( "/" , $_SERVER['PATH_INFO'] );
        		$param = $pa[1];
			}
		}
		/* It doesn't work with php4isapi.dll.
		if($param == 0){
			$tmp = explode('/', $_SERVER['REQUEST_URI']);
			$param = ($tmp[count($tmp)-1]);
		}*/
		$param = trim($param);
		//
		//	modified by hoshiyan@hoshiba-farm.com    2004.7.16
		//
		if (isset($HTTP_GET_VARS['today'])) {
			//print_r($HTTP_GET_VARS);
//			if ($HTTP_GET_VARS['today'] == 'on') {	// write a new blog menu
				//echo 'Write a New Blog';
				$today = array();
				$today['user_time'] = xoops_getUserTimestamp(time());
				//echo $today['user_time'];
				if (is_object($xoopsUser)) {
					if ($HTTP_GET_VARS['today'] == 'on') {
						$today['blogid'] = PopnupBlogUtils::get_blogid_from_uid( $xoopsUser->uid());
					}else{
						$today['blogid'] = $HTTP_GET_VARS['today'];
					}
				}else{
					$today['blogid'] = 0;
				}
				//echo 'Uid = '.$today['uid'];
				$today['year'] = strftime("%Y", $today['user_time']);
				$today['month'] = strftime("%m", $today['user_time']);
				$today['date'] = strftime("%d", $today['user_time']);
				$today['hours'] = strftime("%H", $today['user_time']);
				$today['minutes'] = strftime("%M", $today['user_time']);
				$today['seconds'] = strftime("%S", $today['user_time']);
				$cmd = 0;
				$param = PopnupBlogUtils::makeParams($today['blogid'], $today['year'],$today['month'],$today['date'],$today['hours'], $today['minutes'], $today['seconds'], $cmd );
				//print_r($param);
				//print_r($today);
//			}
		}
//print_r($param);	//	modified end
		if($param == 0){
			return false;
		}
		$result = array();
		$result['year'] = $result['month'] = $result['date'] =
			$result['hours'] = $result['minutes'] = $result['seconds'] = 0;
			$result['command'] = "";
		$result['params'] = $param;
		if ($xoopsUser) $result['uid'] = $xoopsUser->uid();
		$result['blogid'] = $param;
		if (isset($HTTP_GET_VARS['vote'])) $result['vote'] = $HTTP_GET_VARS['vote'];
//print_r($param);
		if(preg_match("/^([0-9]+)-([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})-([a-zA-Z0-9]*)/", $param, $m)){
			$result['blogid'] = PopnupBlogUtils::checkUid($m[1]);
			$result['year'] = PopnupBlogUtils::checkYear($m[2]);
			$result['month'] = PopnupBlogUtils::checkMonth($m[3]);
			$result['date'] = PopnupBlogUtils::checkDate($m[2], $m[3], $m[4]);
			$result['hours']=$m[5];
			$result['minutes']=$m[6];
			$result['seconds']=$m[7];
			$result['command'] = trim($m[8]);		// enc type for MT user
		}elseif(preg_match("/^([0-9]+)-([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/", $param, $m)){
			$result['blogid'] = PopnupBlogUtils::checkUid($m[1]);
			$result['year'] = PopnupBlogUtils::checkYear($m[2]);
			$result['month'] = PopnupBlogUtils::checkMonth($m[3]);
			$result['date'] = PopnupBlogUtils::checkDate($m[2], $m[3], $m[4]);
			//print("$m[5]:$m[6]:$m[7]");
			$result['hours']=$m[5];
			$result['minutes']=$m[6];
			$result['seconds']=$m[7];
		}elseif(preg_match("/^([0-9]+)-([0-9]{4})([0-9]{2})([0-9]{2})/", $param, $m)){
			$result['blogid'] = PopnupBlogUtils::checkUid($m[1]);
			$result['year'] = PopnupBlogUtils::checkYear($m[2]);
			$result['month'] = PopnupBlogUtils::checkMonth($m[3]);
			$result['date'] = PopnupBlogUtils::checkDate($m[2], $m[3], $m[4]);
		}elseif(preg_match("/^([0-9]+)-([0-9]{4})([0-9]{2})/", $param, $m)){
			$result['blogid'] = PopnupBlogUtils::checkUid($m[1]);
			$result['year'] = PopnupBlogUtils::checkYear($m[2]);
			$result['month'] = PopnupBlogUtils::checkMonth($m[3]);
		}elseif(preg_match("/^([0-9]+)/", $param, $m)){
			$result['blogid'] = PopnupBlogUtils::checkUid($m[1]);
		}else{
			redirect_header(XOOPS_URL.'/',1,_MD_POPNUPBLOG_INVALID_DATE.'(INVALID PARAM)');
			exit();
		}
		return $result;
	}
	
	function getApplicationNum(){
		global $xoopsDB;
		if(!$dbResult = $xoopsDB->query('select count(*) num from '.POPNUPBLOG_TABLE_APPL)){
			return 0;
		}
		if(list($num) = $xoopsDB->fetchRow($dbResult)){
			return $num;
		}
		return 0;
	}
	/**
	 * create new blog user
	 */
	function createNewBlogUser($uid='',$gid=0,$cat_id=0,$permission=0,$title='',$desc='',$email='',$emailalias=''){
		global $xoopsUser,$xoopsDB,$BlogCNF;
		
		$result = $xoopsDB->query('select count(*) from '.POPNUPBLOG_TABLE_INFO.' where uid = '.$uid);
		list($count) = $xoopsDB->fetchRow($result);
		if( $count > $BlogCNF['maxuserblogs'] ){
			return false;
		}else{
			$sql='insert into '.POPNUPBLOG_TABLE_INFO.
				' (uid, groupid, cat_id, blog_permission, last_update, title, blog_desc, email) values ('.$uid.', '.intval($gid).', '.intval($cat_id).', '.intval($permission) 
				.', \'0000-00-00\', \'' .PopnupBlogUtils::convert2sqlString($title) .'\',\'' .$desc.'\',\''.$email.'\')';
			$ret = $xoopsDB->queryF($sql);
			if ($ret){
				$result = $xoopsDB->query('SELECT blogid FROM '.POPNUPBLOG_TABLE_INFO.' Where uid='.$uid.' and title=\''.$title.'\'');
				list($blogid) = $xoopsDB->fetchRow($result);
				if ($email && $emailalias){
					if ($blogid) PopnupBlogUtils::createEmailAliasInfo($blogid,$emailalias);
				}
				// Delete From Waiting list
				$result = $xoopsDB->query('select uid from '.POPNUPBLOG_TABLE_APPL.' where uid = '.$uid);
				if(list($uid) = $xoopsDB->fetchRow($result)){
					$xoopsDB->queryF('delete from '.POPNUPBLOG_TABLE_APPL.' where uid = '.$uid);
				}
				// Notify New Blog
				$notification_handler = & xoops_gethandler( 'notification' );
				$tags = array();
				$tags['BLOG_NAME'] = $title;
				$tags['BLOG_DESCRIPTION'] = $desc;
				$tags['BLOG_URL'] =  PopnupBlogUtils::createUrl($blogid);
				$notification_handler -> triggerEvent( 'global', 0, 'new_blog', $tags );
				$notification_handler -> subscribe('global', 0, 'new_blog');
				return true;
			}
		}
	}
	
	function weblogUpdatesPing($rss, $url, $blog_name = null, $title = null, $excerpt = null){
		$ping = new PopnupBlogPing2($rss, $url, $blog_name, $title, $excerpt);
		$ping->send();
		/* debug log
		ob_start();
		print_r($ping);
		$oblog = ob_get_contents();
		ob_end_clean();
		PopnupBlogUtils::log($oblog);
		*/
	}
	
	function newApplication($in_title, $in_desc, $in_permission, $in_gid, $in_cid, $in_email, $in_emailalias){
		global $xoopsUser, $xoopsDB, $adminUid, $BlogCNF;
		$title = "";
		$desc = "";
		$permission = -1;
		if(!empty($in_title)){
			$title = PopnupBlogUtils::convert2sqlString($in_title);
		}
		if(!empty($in_desc)){
			$desc = PopnupBlogUtils::convert2sqlString($in_desc);
		}
		if( ($in_permission >= 0) && ($in_permission < 512) ){
			$permission = intval($in_permission);
		}
		
		if($permission < 0){
			return _MD_POPNUPBLOG_ERR_INVALID_PERMISSION;
		}
		if(!$result = $xoopsDB->query('select uid from '.POPNUPBLOG_TABLE_APPL.' where uid = '.$xoopsUser->uid())){
			return "select error";
		}
		if(list($tmpUid) = $xoopsDB->fetchRow($result)){
			return _MD_POPNUPBLOG_ERR_APPLICATION_ALREADY_APPLIED;
		}
		if(!$result = $xoopsDB->query('select blogid from '.POPNUPBLOG_TABLE_INFO.' where title=\''.$in_title.'\' limit 1')){
			return "select error";
		}
		if(list($blogid) = $xoopsDB->fetchRow($result)){
			return _MD_POPNUPBLOG_ERR_APPLICATION_ALREADY_TITLED;
		}
		if(!$result = $xoopsDB->query('select count(*) from '.POPNUPBLOG_TABLE_INFO.' where uid = '.$xoopsUser->uid())){
			return "select error";
		}
		if(list($num) = $xoopsDB->fetchRow($result)){
			if( $num > $BlogCNF['maxuserblogs'] )
				return _MD_POPNUPBLOG_ERR_MAXBLOGS;
		}
		$sql = sprintf("insert into %s (uid, groupid, cat_id, title, blog_desc, permission, create_date, email, emailalias) values(%u, %u, %u, '%s', '%s', %u, CURRENT_TIMESTAMP(), '%s', '%s')", 
			POPNUPBLOG_TABLE_APPL, $xoopsUser->uid(), $in_gid, $in_cid, $title, $desc, $permission, $in_email, $in_emailalias);
		if(!$result = $xoopsDB->query($sql)){
			return "insert error";
		}
		$email = popnupblog::getEmailByUid($xoopsUser->uid());
		if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$", $email)) { 
			$email="";
			echo "<font color=\"red\">email address error</font>"; 
		}
		$admin_approve = PopnupBlogUtils::getXoopsModuleConfig('activation_type');
		if ($admin_approve==0){
			if(PopnupBlogUtils::createNewBlogUser($xoopsUser->uid(),$in_gid,$in_cid,$permission,$title,$desc,$email) ){
				$msg = "Succeed: ";
			}else{
				$msg = "Failed: ";
			}
			$msg .= "Create blog uid=".$xoopsUser->uid()." title=".$title." email=".$email;
			if ($email) mail($email,"Create new blog",$msg);
		} elseif( !$adminUid ) {
			$msg = "Request blog uid=".$xoopsUser->uid()." title=".$title." email=".$email;
			if ($email) mail( popnupblog::getEmailByUid($adminUid),"request new blog",$msg);
		}
		return "";
	}
	function deleteApplication($uid){
		global $xoopsDB;
		$uid = intval($uid);
		if($uid > 0){
			 $xoopsDB->queryF(sprintf('delete from %s where uid = %u', POPNUPBLOG_TABLE_APPL, $uid));
		}
	}
	function getBlogInfo( $uid=0 ){
		global $xoopsDB;

		//$myts =& MyTextSanitizer::getInstance();
		$member_handler =& xoops_gethandler('member');
		$groupnames = $member_handler->getGroupList(); 
		$categories = PopnupBlogUtils::get_categories();
		$i = 0;
		$users = array();
		$wstr='';
		if ($uid>0) $wstr = " Where uid=".$uid;
		$result = $xoopsDB->query('SELECT uid, blogid, groupid, cat_id, blog_permission, DATE_FORMAT(last_update, \'%Y-%m-%d\') last_update, title, blog_desc, email FROM '.POPNUPBLOG_TABLE_INFO.$wstr.' order by uid, blogid');
		while( list($uid, $blogid, $gid, $cat_id,  $permission, $lastUpdate, $blogTitle, $blogdesc, $blogemail) = $xoopsDB->fetchRow($result) ){
			$users[$i]['uid'] = $uid;
			$users[$i]['bid'] = $blogid;
			$users[$i]['gid'] = $gid;
			$users[$i]['cat_id'] = $cat_id;
			$users[$i]['cidselect'] = PopnupBlogUtils::mkselect('cat_id',$categories, $cat_id);
			$users[$i]['gidselect'] = PopnupBlogUtils::mkselect('gid',$groupnames, $gid);
			$users[$i]['canread'] = $permission & 0x07;
			$users[$i]['cancomment'] = ($permission & 0x38)>>3;
			$users[$i]['canvote'] = ($permission & 0x1c0)>>6;
			$users[$i]['lastUpdate'] = $lastUpdate;
			$users[$i]['title'] = $blogTitle;	//$myts->makeTareaData4Edit();
			$users[$i]['desc'] = $blogdesc;	//$myts->makeTareaData4Edit();
			$users[$i]['email'] = $blogemail;
			//$users[$i]['emailalias'] = array;          // Modified by hoshiyan@hoshiba-farm.com 2004.8.4
			$s = "SELECT email,uid FROM ".POPNUPBLOG_TABLE_EMAIL_ALIAS." WHERE blogid = $blogid and public = 1";
			$r = $xoopsDB->query($s);
			if ($r){	//$fa = $xoopsDB->fetchArray($r);
				$users[$i]['emailalias'] = $r;		//$fa['email'];
				$users[$i]['emailalias_options'] = PopnupBlogUtils::b_mailalias_show($users[$i]['emailalias']);
			}
			$s = "SELECT email,uid FROM ".POPNUPBLOG_TABLE_EMAIL_ALIAS." WHERE blogid = $blogid and public = 2";
			$r = $xoopsDB->query($s);
			if ($r){
				$users[$i]['emailsends'] = $r;
				$users[$i]['emailsends_options'] = PopnupBlogUtils::b_mailalias_show($users[$i]['emailsends']);
			 }
			//print_r ($users[$i]);
			$i++;
		}
		return $users;
	}
	function b_mailalias_show($options){
		global $xoopsDB;
		$unames = PopnupBlogUtils::get_unames();
		$email_options = '';
		while ($row = $xoopsDB->fetchArray($options)){
			$email_options .= '<option value="'.$row['email'].'"';
			$email_options .= '>'.$unames[$row['uid']].'&lt;'.$row['email'].'&gt;</option>';
		}
		return $email_options;
	}
	function mailalias_delete($bid,$pid,$emailalias){
		global $xoopsDB;
		while(list($null,$email) = each($emailalias)){
			$sql = "DELETE FROM ".$xoopsDB->prefix("popnupblog_emailalias")." Where blogid=$bid and public=$pid and email='$email'";
			if (!$result = $xoopsDB->query($sql)){
				return $result;
			}
		}
	}
	function mailalias_add($bid,$pid,$email,$uid=0){
		global $xoopsDB;
		if(!$email) $email = popnupblog::getEmailByUid($uid);
		$sql = "INSERT INTO ".$xoopsDB->prefix("popnupblog_emailalias")." (blogid, public, email, uid) VALUES ($bid, $pid, '$email',$uid)";
		return $xoopsDB->query($sql);
	}

	/* {{{ proto string mkselect(string name, array options)
	   Returns HTML format for a select box (dropdown). */
	function mkselect ($_name, $options, $varr = null) {
	    if ($varr == null)
	        $varr =& $GLOBALS['HTTP_POST_VARS'];
		$str  = "<select name=\"${_name}\">\n";
		$str .= "<option></option>\n";
		while(list($cid, $content) = each($options)) {
			$checked = '';
			if (isset($varr[$_name]) && $varr[$_name] == $cid)
				$checked = ' selected';
			if (intval($varr) == $cid)
				$checked = ' selected';
			$str .= "<option value=\"${cid}\"${checked}>${content}</option>\n";
		}
		$str .= "</select>\n";
		return($str);
	}
	/* }}} */
	
	function getXoopsModuleConfig($key){
		global $xoopsDB;
		$mid = -1;

		$sql = "SELECT mid FROM ".$xoopsDB->prefix('modules')." WHERE dirname = 'popnupblog'";
		if (!$result = $xoopsDB->query($sql)) {
			return false;
		}
		$numrows = $xoopsDB->getRowsNum($result);
		if ($numrows == 1) {
			list($l_mid) = $xoopsDB->fetchRow($result);
			$mid = $l_mid;
		}else{
			return false;
		}
		$sql = "select conf_value from ".$xoopsDB->prefix('config')." where conf_modid = ".$mid." and conf_name = '".trim($key)."'";
		if (!$result = $xoopsDB->query($sql)) {
			return false;
		}
		$numrows = $xoopsDB->getRowsNum($result);
		if ($numrows == 1) {
			list($value) = $xoopsDB->fetchRow($result);
			//return intval($value);
			return $value;
		}else{
			return false;
		}
	}
	function getComment1($cid){
		global $xoopsUser,$xoopsDB;
		$sql = 'select blogid,comment_uid, post_text,vote FROM '.POPNUPBLOG_TABLE_COMMENT.' WHERE comment_id = '.$cid;
		if(!$result_select = $xoopsDB->query($sql)){
			return false;
		}
		$result = array();
		$ts =& MyTextSanitizer::getInstance();
		if(list($blogid,$comment_uid,$text,$vote) = $xoopsDB->fetchRow($result_select)){
			$result['blogid'] = $blogid;
			$result['comment_uid'] = $comment_uid;
			$result['text'] = $ts->makeTareaData4Show($text);
			$result['text_edit'] = $ts->makeTareaData4Edit($text);
			$result['vote'] = $vote;
		}
		return $result;
	}
	function updateComment($comment_uid, $comment_id, $comment='', $updatevote=0){
		global $xoopsUser,$xoopsDB;
		$uid = 0;
		if($xoopsUser){
			$uid = $xoopsUser->uid();
		}
		if($xoopsUser->isAdmin()){
			$uid = $comment_uid;
		}
		$comment = htmlspecialchars($comment);
		$sqlComment = PopnupBlogUtils::convert2sqlString($comment); 
		// Get Current Comment
		$sql = sprintf("select blogid,blog_date,comment_name,vote from %s where comment_uid = %u and comment_id = %u", POPNUPBLOG_TABLE_COMMENT, $uid,$comment_id);
		$result_select = $xoopsDB->query($sql);
		if(!list($blogid,$blog_date,$comment_name,$vote) = $xoopsDB->fetchRow($result_select)){
			return false;
		}
		// Delete Comment
		if(empty($sqlComment) and $updatevote==0){
			// Cancel for voted
			$sql = sprintf("select blogid,blog_date,vote from %s where comment_uid = %u and comment_id = %u", POPNUPBLOG_TABLE_COMMENT, $uid,$comment_id);
			$result_select = $xoopsDB->query($sql);
			if(list($blogid,$blog_date,$vote) = $xoopsDB->fetchRow($result_select)){
				if($vote==1){
					$sql = sprintf("update %s set votes_yes = votes_yes-1 where blogid = %u and blog_date ='%s'", POPNUPBLOG_TABLE_BLOG, $blogid, $blog_date);
				}elseif($vote==-1){
					$sql = sprintf("update %s set votes_no = votes_no-1 where blogid = %u and blog_date ='%s'", POPNUPBLOG_TABLE_BLOG, $blogid, $blog_date);
				}
				$result = $xoopsDB->queryF($sql);
			}
			if (empty($sqlComment)){
				$sql = sprintf("delete from %s where comment_uid = %u and comment_id = %u", POPNUPBLOG_TABLE_COMMENT, $uid,$comment_id);
			}else{
				$sql = sprintf("update %s set vote = 0 where comment_uid = %u and comment_id = %u", POPNUPBLOG_TABLE_COMMENT, $uid,$comment_id);
			}
			$result = $xoopsDB->queryF($sql);
			return true;
		} else {
			// Do Update
			$sql_base = "update %s set post_text = '%s', create_date = '%s', vote = '%d' where comment_uid = %u and comment_id = %u";
			$sql = sprintf($sql_base, POPNUPBLOG_TABLE_COMMENT, $sqlComment, date("Y-m-d H:i:s",time()),$updatevote,$uid,$comment_id);
			$result = $xoopsDB->queryF($sql);
		}
		$sql='';
		if ($vote==-1 && $updatevote==1){
			$sql = sprintf("update %s set votes_no = votes_no - 1 where blogid = %u and blog_date ='%s'", POPNUPBLOG_TABLE_BLOG, $blogid, $blog_date);
		}elseif ($vote==1 && $updatevote==-1){
			$sql = sprintf("update %s set votes_yes = votes_yes - 1 where blogid = %u and blog_date ='%s'", POPNUPBLOG_TABLE_BLOG, $blogid, $blog_date);
		}elseif ($vote==0 && $updatevote==1){
			$sql = sprintf("update %s set votes_yes = votes_yes + 1 where blogid = %u and blog_date ='%s'", POPNUPBLOG_TABLE_BLOG, $blogid, $blog_date);
		}elseif ($vote==0 && $updatevote==-1){
			$sql = sprintf("update %s set votes_no = votes_no + 1 where blogid = %u and blog_date ='%s'", POPNUPBLOG_TABLE_BLOG, $blogid, $blog_date);
		}
		if ($sql) $result = $xoopsDB->queryF($sql);
		$mailto = PopnupBlogUtils::get_email_from_blogid($blogid);
		if (!empty($mailto)){
			$sql = sprintf("select title from %s where uid = %u and blog_date = '%s'",POPNUPBLOG_TABLE_BLOG, $blogid, $blog_date);
			$result = $xoopsDB->fetchArray($xoopsDB->query($sql));
			popnupblog::send_comment($mailto,$result['title'], $comment_name,$sqlComment, $xoopsUser->uname());
		}
		return true;
	}
	
	function get_RecentlyComment($bid,$blogdate){
		global $xoopsUser, $xoopsDB;
		$sql = 'select comment_uid,comment_name,post_text FROM '.POPNUPBLOG_TABLE_COMMENT.' WHERE blogid = '.$bid.' and blog_date = \''.$blogdate.'\' order by comment_id desc limit 1;';
		if(!$result_select = $xoopsDB->query($sql)){
			return false;
		}
		$result = array();
		if(list($uid,$uname,$comment) = $xoopsDB->fetchRow($result_select)){
			$show_name = PopnupBlogUtils::getXoopsModuleConfig('show_name');
			if ( $show_name==1 && (trim(PopnupBlogUtils::username($uid)!='')))
				$result['uname'] = PopnupBlogUtils::username($uid);
			else
				$result['uname'] = $uname;
			$result['comment'] = $comment;
		}
		return $result;
	}	
	function get_RecentlyBlog($bid){
		global $xoopsUser, $xoopsDB;
		$sql = 'select blog_date,title,post_text FROM '.POPNUPBLOG_TABLE_BLOG.' WHERE blogid = '.$bid.' order by blog_date desc limit 1;';
		if(!$result_select = $xoopsDB->query($sql)){
			return false;
		}
		$result = array();
		if(list($blog_date,$title,$post_text) = $xoopsDB->fetchRow($result_select)){
			$result['blog_date'] = $blog_date;
			$result['title'] = $title;
			$result['text'] = $post_text;
		}
		return $result;
	}	
	function your_private(){
		global $xoopsUser, $xoopsDB;
		if ( $xoopsUser ) {
			$sql = 'select blogid from '.POPNUPBLOG_TABLE_EMAIL_ALIAS.' where uid = '.$xoopsUser->uid();
			if($result = $xoopsDB->query($sql)){
				$bids='';
				while( list($blogid) = $xoopsDB->fetchRow($result) ){
					if ( strlen($bids)>0 ) $bids .= ',';
					$bids .= $blogid;
				}
				if ( strlen($bids)>0 ) return 'blogid in ('.$bids.')';
			}
		}
	}
	function get_blog_list($start = 0, $cat_id=0){
		global $xoopsUser, $xoopsDB;

		$useRerite = PopnupBlogUtils::getXoopsModuleConfig('POPNUPBLOG_REWRITE');
		$categories = PopnupBlogUtils::get_categories();
		$block_list_num = 10;
		$dateFormat = '%m/%d %k:%i';

		$permission = 0;
		$uid=0;
		if ( $xoopsUser ) {
			if($xoopsUser->isAdmin()){
				$permission = 7;
			} elseif ( $xoopsUser->getVar('rank')>=2 ) {
				$permission = $xoopsUser->getVar('rank');
			} else {
				$permission = 1;//0x20 + 0x08 + 0x02;
			}
			$uid = $xoopsUser->uid();
		}
		$selectMax = $start + POPNUPBLOG_BLOCK_LIST_NUM;
		$wstr='';
		if($cat_id>0) $wstr=" and cat_id=".$cat_id;
		$pbids = PopnupBlogUtils::your_private();
		if ($pbids) $pbids = ' || '.$pbids;
		$sql_select = sprintf('select uid, blogid, cat_id, UNIX_TIMESTAMP(last_update) last_update,  title, blog_desc  FROM %s '.
			'WHERE ((blog_permission & 0x07) <= %u || uid=%u '.$pbids.') and last_update != \'0000-00-00\''.$wstr.' ORDER BY last_update desc limit %u',
			 POPNUPBLOG_TABLE_INFO, $permission,$uid, $selectMax);
		if(!$result_select = $xoopsDB->query($sql_select)){
			return false;
		}
		$rblog = array();
		$rcomment = array();
		$tmp = array();
		$i = 0;
		$ts =& MyTextSanitizer::getInstance();
		while(	list(
				$result_uid, 
				$result_bid, 
				$result_cid, 
				$result_last_update,
				$title,
				$desc,
			) = $xoopsDB->fetchRow($result_select)
		){
			if($i >= $start){
				$res = array();
				$res['uid'] = $result_uid;
				if ($result_cid) $res['catname'] = $categories[$result_cid];
				$res['last_update'] = $result_last_update;
				$res['last_update_s'] = formatTimestamp($result_last_update, 's');
				$res['last_update_m'] = formatTimestamp($result_last_update, 'm');
				$res['last_update_l'] = formatTimestamp($result_last_update, 'l');
				$res['title'] = $title;
				$res['desc'] = $ts->makeTareaData4Show($desc);
				$rblog = PopnupBlogUtils::get_RecentlyBlog($result_bid);
				if($rblog){
					$res['last_title'] = $rblog['title'];
					if ($GLOBALS['BlogCNF']['blockview']==1){
						if ($GLOBALS['BlogCNF']['text_limit']>0)
							$res['last_text'] = $ts->makeTareaData4Show(
								PopnupBlogUtils::phpbbsmiley(
								PopnupBlogUtils::_strcut($rblog['text'],0,$GLOBALS['BlogCNF']['text_limit'])
								)
							);
					} else {
						$res['last_text'] = $ts->makeTareaData4Show(PopnupBlogUtils::phpbbsmiley($rblog['text']));
					}
					$res['url'] = PopnupBlogUtils::createUrl($result_bid);
					$rcomment = PopnupBlogUtils::get_RecentlyComment($result_bid,$rblog['blog_date']);
					if($rcomment){
						$res['commentuname'] = $rcomment['uname'].": ";
						$res['comment'] = $rcomment['comment'];
					}
				}
				$tmp[$i] = $res;
			}
			$i++;
		}
		$block = array();
		$userHander = new XoopsUserHandler($xoopsDB);
		$i = 0;
		foreach ( $tmp as $target ) {
			$tUser = $userHander->get($target['uid']);
			$show_name = PopnupBlogUtils::getXoopsModuleConfig('show_name');
			if ( $show_name==1 && (trim(PopnupBlogUtils::username($target['uid']))!='') )
				$target['uname'] = PopnupBlogUtils::username($target['uid']);
			else
				if($tUser) $target['uname'] = $tUser->uname();


			$target['last_update4rss'] =  PopnupBlogUtils::toRssDate($target['last_update']);
			if(empty($target['title'])){
				$target['title'] = _MD_POPNUPBLOG_TITLE_PREFIX.$target['uname']._MD_POPNUPBLOG_TITLE_SUFFIX;
			}
			$block[$i] = $target;
			$i++;
		
		}
		return $block;
	}
	
	function createRssURL($uid){
		$useRerite = PopnupBlogUtils::getXoopsModuleConfig('POPNUPBLOG_REWRITE');
		if((empty($useRerite)) || ($useRerite == 0) ){
			return POPNUPBLOG_DIR.'rss.php'.POPNUPBLOG_REQUEST_URI_SEP.$uid;
		}else{
			return POPNUPBLOG_DIR.'rss/'.$uid.".xml";
		}
	}
	
	function createUrl($blogid, $year = 0, $month = 0, $date = 0, $hours = 0, $minutes = 0, $seconds = 0, $command = null){
		return XOOPS_URL."/modules/popnupblog/".PopnupBlogUtils::createUrlNoPath($blogid, $year, $month, $date, $hours, $minutes, $seconds, $command);
	}
	
	function createUrlNoPath($blogid, $year = 0, $month = 0, $date = 0, $hours = 0, $minutes = 0, $seconds = 0, $command = null){
		$useRerite = PopnupBlogUtils::getXoopsModuleConfig('POPNUPBLOG_REWRITE');
		$result = '';
		if((empty($useRerite)) || ($useRerite == 0) ){
			$result .= "index.php".POPNUPBLOG_REQUEST_URI_SEP.PopnupBlogUtils::makeParams($blogid, $year, $month, $date, $hours, $minutes, $seconds, $command);
		}else{
			$result .= "view/".PopnupBlogUtils::makeParams($blogid, $year, $month, $date, $hours, $minutes, $seconds, $command).".html";
		}
		return $result;
	}
	//
	// modified by hoshiyan@hoshiba-farm.com  2005.02.03
	//
	function _strcut($text, $start, $end){
		$text = PopnupBlogUtils::formatBlogText4Preview($text);
		if ( strlen($text) >= $end ) {
			$text =xoops_substr($text, 0, $end-1);
		}
		return $text;
	}
	//
	// added by hoshiyan,hoshiba-farm.com, 2004-10-15
	//
	function formatBlogText4Preview($srcStr) {
		$dstStr = preg_replace("/\[(url|img)[^]]*\].*\[\/(url|img)\]/","",$srcStr);
		$dstStr = strip_tags($dstStr);
		$dstStr = preg_replace("/([\r\n])[\s]+/","",$dstStr);
		return $dstStr;
    }
	//
	//
	function toRssDate($time, $timezone = null){
		//if(!empty($timezone)){
		//	$time = xoops_getUserTimestamp($time);
		//}
		$res =  date("Y-m-d\\TH:i:sO", $time);
		// mmmm
		$result = substr($res, 0, strlen($res) -2).":".substr($res, -2);
		return $result;
	}
	
	function checkUid($iuid){
		$uid = intval($iuid);
		if( $uid > 0){
			return $uid;
		}
	}

	function checkYear($iyear){
		$year = intval($iyear);
		if ( ($year > 1000) && ($year < 3000) ){
			return $iyear;
		}
		redirect_header(XOOPS_URL.'/',1,_MD_POPNUPBLOG_INVALID_DATE.'(YEAR)'.$iyear);
		exit();
	}
	
	function checkMonth($imonth){
		$month = intval($imonth);
		if ( ($month > 0) && ($month < 13) ){
			return $imonth;
		}
		redirect_header(XOOPS_URL.'/',1,_MD_POPNUPBLOG_INVALID_DATE.'(MONTH)');
		exit();
	}
	
	function checkDate($year, $month, $date){
		if(checkdate(intval($month), intval($date), intval($year))){
			return $date;
		}
		redirect_header(XOOPS_URL.'/',1,_MD_POPNUPBLOG_INVALID_DATE.'(ALL DATE) '.intval($year)."-".intval($month)."-". intval($date));
		exit();
	}
	
	function makeParams($blogid, $year=0, $month=0, $date=0, $hours=0, $minutes=0, $seconds=0, $command = null){
		$result = '';
		$c = '';
		if(!empty($command)){
			$c = '-'.$command;
		}
		if($year == 0){
			$result = $blogid;
		}elseif($date == 0){
			$result = sprintf("%s-%04u%02u%s", "".$blogid, $year, $month, $c);
		}else{
			$result = sprintf("%s-%04u%02u%02u%02u%02u%02u%s", "".$blogid, $year, $month, $date, $hours, $minutes, $seconds, $c);
		}
		return $result;
	}
	
	function makeTrackBackURL($blogid, $year = 0, $month = 0, $date = 0, $hours=0, $minutes=0, $seconds=0){
		$tburl = XOOPS_URL.'/modules/popnupblog/trackback.php'.POPNUPBLOG_TRACKBACK_URI_SEP.PopnupBlogUtils::makeParams($blogid, $year, $month, $date, $hours, $minutes, $seconds);
		return $tburl;
	}
	
	function isCompleteDate($d){
		if(!empty($d['year'])){
			if(checkdate(intval($d['month']), intval($d['date']), intval($d['year']))){
				return true;
			}
		}
		return false;
	}
	function complementDate($d){
		if(!checkdate(intval($d['month']), intval($d['date']), intval($d['year']))){
			$time = time();
			$d['year'] = date('Y',$time);
			$d['month'] = sprintf('%02u', date('m',$time));
			$d['date'] =  sprintf('%02u', date('d',$time));
			$d['hours'] =  sprintf('%02u', date('H',$time));
			$d['minutes'] =  sprintf('%02u', date('i',$time));
			$d['seconds'] =  sprintf('%02u', date('s',$time));
		}
		//print($d['hours'].$d['minutes'].$d['seconds']);
		return $d;
	}
	
	function convert_encoding(&$text, $from = 'auto', $to){
		if(function_exists('mb_convert_encoding')){
			return mb_convert_encoding($text, $to, $from); 
		} elseif (function_exists('iconv')){
			return iconv($from, $to, $text);
		} elseif (function_exists('JcodeConvert')) {
			return JcodeConvert($str, 0, 1);
		}else{
			return $text;
		}
	}
	
	function assign_message(&$tpl){
		$all_constants_ = get_defined_constants();
		foreach($all_constants_ as $key => $val){
			if(preg_match("/^_(MB|MD|AM|MI)_POPNUPBLOG_(.)*$/", $key) || preg_match("/^POPNUPBLOG_(.)*$/", $key)){
				if(is_array($tpl)){
					$tpl[$key] = $val;
				}elseif(is_object($tpl)){
					$tpl->assign($key, $val);
				}
			}
		}
	}
	/*
	function get_recent_trackback($date){
		global $xoopsDB;
		$sql = 'select title, url from '.POPNUPBLOG_TABLE_TRACKBACK.' where blogid = '.$date['blogid'].' order by t_date desc';
		if(!$db_result = $this->xoopsDB->query($sql)){
			return false;
		}
		$i = 0;
		
		$result['html'] = '<div>';
		while(list($title, $url) = $this->xoopsDB->fetchRow($db_result)){
			$result[data][] = new array(){ 'title' => $title, 'url' => $url};
			$i++;
			$result['html'] .= '<a href="'.$url.'" target="_blank">'.$title.'</a><br />';
		}
		$result['html'] .= '</div>';
		
		return $result;
	}
	*/
	function send_trackback_ping($trackback_url, $url, $title, $blog_name, $excerpt = null) {
		PopnupBlogPing2::send_trackback_ping($trackback_url, $url, $title, $blog_name, $excerpt) ;
	}
	
	
	function remove_html_tags($t){
		return preg_replace_callback(
			"/(<[a-zA-Z0-9\"\'\=\s\/\-\~\_;\:\.\n\r\t\?\&\+\%\&]*?>|\n|\r)/ms", 
			/* "/(<[*]*?>|\n|\r)/ms", */
			"popnupblog_remove_html_tags_callback", 
			$t);
	}
	
	
	function convert2sqlString($text){
		$ts =& MyTextSanitizer::getInstance();
		if(!is_object($ts)){
			exit();
		}
		$res = $ts->stripSlashesGPC($text);
		$res = $ts->censorString($res);
		$res = addslashes($res);
		return $res;
	}
	//
	//  Modified by hoshiyan@hoshiba-farm.com 2004.8.5
	//
	function createEmailAliasInfo($blogid='', $email = ''){
		global $xoopsUser,$xoopsDB;

		$debug = 0;
		// this query is just for convenience of novice user.
		$sqlcmd = 'create table if not exists '.POPNUPBLOG_TABLE_EMAIL_ALIAS.' (blogid int(5) unsigned not null default 0, public tinyint(1) not null default 1, email varchar(60), primary key(blogid))';
		if ($debug){ echo $sqlcmd; }
		$result = $xoopsDB->queryF($sqlcmd);
		if ($debug){ echo $result; }
		
		$sqlcmd = 'select * from '.POPNUPBLOG_TABLE_EMAIL_ALIAS.' where blogid = '.$blogid.' and email =\''.$email.'\'';
		if ($debug){ echo $sqlcmd; }
		$result = $xoopsDB->query($sqlcmd);
		if ($debug){ echo $result; }
		if($result){
			$sqlcmd = 'insert into '.POPNUPBLOG_TABLE_EMAIL_ALIAS.' set blogid ='.$blogid.', public = 1, email =\''.$email.'\'';
			if ($debug){ echo $sqlcmd; }
			$result = $xoopsDB->queryF($sqlcmd);
			if ($debug){ echo $result; }
		}
		return true;
	}
	//
	//  Modified by Yoshi.Sakai 2004.8.31
	//
	function setEmailAliasInfo($blogid='', $email = ''){
		global $xoopsUser,$xoopsDB;

		$debug = 0;
		$sql = sprintf('SELECT blogid, public, email from %s where blogid=%u', POPNUPBLOG_TABLE_EMAIL_ALIAS,$blogid);
		if ($debug){ echo $sql; }
		$qResult = $xoopsDB->query($sql);
		list($bid,$public,$cur_email) = $xoopsDB->fetchRow($qResult);
		if ($debug){ echo " blogid = (".$bid.")"; }
		if(!$bid){
			PopnupBlogUtils::createEmailAliasInfo($blogid, $email);
		} else {
			$sql = 'update '.POPNUPBLOG_TABLE_EMAIL_ALIAS.' set public=1, email=\''.$email.'\' where blogid ='.$blogid;
			if ($debug){ echo $sql; }
			$qResult = $xoopsDB->query($sql);
			if ($debug){ echo $qResult; }
		}
		return true;
	}
	function mail_popimg(){
		global $log,$limit_min;
		$host = PopnupBlogUtils::getXoopsModuleConfig('MAILSERVER');
		if ($host==null || strlen($host)==0) return "Without Mail Option.";
		if (filemtime($log) < time() - $limit_min * 60) {
			return "<div style=\"text-align:center;\"><img src=./pop.php?img=1&time=".time()."\" width=70 height=1 /></div>Poped";
		} else {
			return "Snoozed";
		}
	}
	function get_email_from_blogid( $blogid ){
		global $xoopsDB;
		$rawuid = $xoopsDB->fetchArray($xoopsDB->query("SELECT email FROM ".POPNUPBLOG_TABLE_INFO." WHERE blogid = '".$blogid."' limit 1"));
		return $rawuid['email'];
	}
	function get_uid_from_blogid( $blogid ){
		global $xoopsDB;
		$rawuid = $xoopsDB->fetchArray($xoopsDB->query("SELECT uid FROM ".POPNUPBLOG_TABLE_INFO." WHERE blogid = '".$blogid."' limit 1"));
		return $rawuid['uid'];
	}
	function get_blogid_from_email( $email , $blogid ){
		global $xoopsDB;
		$rawuid = $xoopsDB->fetchArray($xoopsDB->query("SELECT blogid FROM ".POPNUPBLOG_TABLE_INFO." WHERE blogid = '".$blogid."' and email = '".$email."' limit 1"));
		if($rawuid['blogid']) return $rawuid['blogid'];
		$rawuid = $xoopsDB->fetchArray($xoopsDB->query("SELECT blogid FROM ".POPNUPBLOG_TABLE_EMAIL_ALIAS." WHERE blogid = '".$blogid."' and email = '".$email."' limit 1"));
		if($rawuid['blogid']) return $rawuid['blogid'];
		return null;
	}
	function get_blogid_from_uid( $uid ){
		global $xoopsDB;
		$rawuid = $xoopsDB->fetchArray($xoopsDB->query("SELECT blogid FROM ".POPNUPBLOG_TABLE_INFO." WHERE uid=".$uid." limit 1"));
		return $rawuid['blogid'];
	}
	function get_bloginfo( $uid ){
		global $xoopsDB;
		if(!$result = $xoopsDB->query("SELECT blogid,title FROM ".POPNUPBLOG_TABLE_INFO." WHERE uid=".$uid)){
			return false;
		}
		$ret = array();
		while(list($blogid,$title)=$xoopsDB->fetchRow($result)){
			$ret[$blogid]=$title;
		}
		return $ret;
	}
	function get_categories(){
		global $xoopsDB;

		if(!$result = $xoopsDB->query("SELECT cat_id,cat_title FROM ".$xoopsDB->prefix("popnupblog_categories")." order by cat_order")){
			return false;
		}
		$ret = array();
		while(list($cat_id,$cat_title)=$xoopsDB->fetchRow($result)){
			$ret[$cat_id]=$cat_title;
		}
		return $ret;
	}
	function mk_list_url($cat_id=0,$view=0){
		global $xoopsDB,$start;
		$sql_where = '';
		if ($cat_id>0) $sql_where = ' and cat_id = '.$cat_id;
		$n = 1;
		$urls = '';
		$nurl = '';
		$cflg = false;
		$sql = "select count(*) from ".POPNUPBLOG_TABLE_INFO." Where last_update != 0".$sql_where;
		if(list($num) = $xoopsDB->fetchRow($xoopsDB->query($sql))){
			for ($i=0;$i<$num;$i+=POPNUPBLOG_BLOCK_LIST_NUM){
				$cstart=$i.",".POPNUPBLOG_BLOCK_LIST_NUM;
				if ($start==$cstart){
					$nstr='('.$n.')';
					$cflg=true;
				} else {
					if ($cflg==true)
						$nurl='<a href="'."index.php".POPNUPBLOG_REQUEST_URI_SEP.'&start='.$cstart.'&cat_id='.$cat_id.'&view='.$view.'"><u>&raquo</u></a>&nbsp';
					$nstr=$n;
					$cflg=false;
				}
				$urls = $urls.'<a href="'."index.php".POPNUPBLOG_REQUEST_URI_SEP.'&start='.$cstart.'&cat_id='.$cat_id.'&view='.$view.'">'.$nstr.'</a>&nbsp';
				$n++;
			}
			$urls = $urls.$nurl;
		}
//		echo $urls;
		return $urls;
	}
	/**
	* Replace emoticons in the message with phpBB images
	* @param	string  $message
	* @return	string
	*/
	function phpBBsmiley($message){
		//print($message);
		$message =& str_replace(":download:", "[img]".XOOPS_URL."/modules/popnupblog/images/attachment.gif[/img]", $message);
		return $message;
	}		
	function username($uid)	{
		global $xoopsDB;
		static $TblUser;
		if (isset($TblUser) && array_key_exists($uid,$TblUser)){
			$ret=$TblUser[$uid];
		}else{
			$sql = "SELECT name FROM ".$xoopsDB->prefix("users")." WHERE uid= $uid";
			$ret = '';
			if ( $result = $xoopsDB->query($sql) ) {
				if ( $myrow = $xoopsDB->fetchRow($result) ){
					$ret = $myrow[0];
				}
			}
			$TblUser[$uid]=$ret;
		}
		return $ret;
	}
	function uname($uid)	{
		global $xoopsDB;
		static $TblUser;
		if (isset($TblUser) && array_key_exists($uid,$TblUser)){
			$ret=$TblUser[$uid];
		}else{
			$sql = "SELECT uname FROM ".$xoopsDB->prefix("users")." WHERE uid= $uid";
			$ret = '';
			if ( $result = $xoopsDB->query($sql) ) {
				if ( $myrow = $xoopsDB->fetchRow($result) ){
					$ret = $myrow[0];
				}
			}
			$TblUser[$uid]=$ret;
		}
		return $ret;
	}
	function get_unames()	{
		global $xoopsDB;
		$sql = "SELECT uid,uname FROM ".$xoopsDB->prefix("users")." order by uid";
		$myrow = array();
		$myrow[0]=null;
		if ( $result = $xoopsDB->query($sql) ) {
			while( list($uid,$uname) = $xoopsDB->fetchRow($result) ){
				$myrow[$uid]=$uname;
			}
			return $myrow;
		}
	}
	function find_uid_mail($uname){
		global $xoopsDB;
		$sql = "SELECT uid,email FROM ".$xoopsDB->prefix("users")." WHERE uname = '$uname'";
		if ( $result = $xoopsDB->query($sql) ) {
			$ret = $xoopsDB->fetchRow($result);
			return $ret;
		}
	}
	function send_mailinglist($from,$to,$uname,$subj,$blogname,$blogurl,$message='',$files) {
		global $xoopsConfig,$BlogCNF;
		$debug = 0;
		$xoopsMailer =& getMailer();
		$xoopsMailer->useMail();
		$xoopsMailer->setTemplateDir($BlogCNF['path']."language/".$xoopsConfig['language']."/mail_template/");
		$xoopsMailer->setTemplate("mailinglist.tpl");
		$xoopsMailer->setToEmails($to);
		$xoopsMailer->assign("POST_TITLE", $subj);
		$xoopsMailer->assign("POST_MESSAGE", $message);
		$xoopsMailer->assign("BLOG_URL", $blogurl);
		$xoopsMailer->assign("SITENAME", $xoopsConfig['sitename']);
		$xoopsMailer->assign("SITEURL", $xoopsConfig['xoops_url']."/");
		$xoopsMailer->assign("BLOG_UNAME", $uname);
		$xoopsMailer->assign("BLOG_MAIL", $from);
		$xoopsMailer->setFromEmail($from);
		$xoopsMailer->setFromName($uname);
		$subj = sprintf(_MD_POPNUPBLOG_MAILINGLIST,$xoopsConfig['sitename'],$blogname);
		if ( function_exists('mb_encode_mimeheader') )
			$subj = mb_encode_mimeheader( $subj, PopnupBlogUtils::get_mailcode(), "B" );
		$xoopsMailer->setSubject($subj);
		if ($debug){ echo "Attached files=".count($files)."<br />"; }
		for($i=0;$i<count($files);$i++) {
			if ($debug){ echo "Path=".$files[$i]['path']." File name=".$files[$i]['name']."<br />"; }
			if (preg_match("/\.(gif|jpe?g|png|bmp)$/i",$files[$i]['path'])){
				$size = getimagesize($files[$i]['path']);
				if ($size[0] <= $GLOBALS['BlogCNF']['w'] && $size[1] <= $GLOBALS['BlogCNF']['h']) {
					// Send Thumbnail or Under Thumbnail size
					$xoopsMailer->multimailer->AddAttachment($files[$i]['path'],$files[$i]['name'],"base64",$size['mime']);
				}
			} else {
				// Send Attach file
				$xoopsMailer->multimailer->AddAttachment($files[$i]['path'],$files[$i]['name']);
			}
		}
		$xoopsMailer->send();
	}
	function send_notify($blogid,$blogname,$blogurl,$subj,$message=''){
		// RMV-NOTIFY
		// Define tags for notification message
		$tags = array();
		$tags['BLOG_NAME'] = $blogname;
		$tags['POST_NAME'] = $subj;
		$tags['POST_URL'] = $blogurl;
		$tags['POST_CONTENT'] = $message;
		$notification_handler =& xoops_gethandler('notification');
		$notification_handler->triggerEvent('blog', $blogid, 'new_post', $tags);
		$notification_handler->triggerEvent('global', 0, 'new_post', $tags);
		$notification_handler->triggerEvent('global', 0, 'new_fullpost', $tags);

		// If user checked notification box, subscribe them to the
		// appropriate event; if unchecked, then unsubscribe

		if (!empty($xoopsUser) && !empty($xoopsModuleConfig['notification_enabled'])) {
			$notification_handler->subscribe('blog', $blogid, 'new_post');
		}

	}
	function send_mailalias($blogid,$from,$uname,$subj,$blogname,$blogurl,$message='') {
		global $xoopsDB;

		$myts =& MyTextSanitizer::getInstance();
		$files = array();
		// Strip img,html,crlf
		if ($GLOBALS['BlogCNF']['mail_view']==1){
			// Make for AddAttachment
			$ret = preg_match_all("/http\:\/\/[\w\.\~\-\/\?\&\+\=\:\@\%\#]+/",$message,$matches);
			for ($i=0; $i< count($matches[0]); $i++) {
				$files[$i]['path'] = preg_replace("'".XOOPS_URL."'",XOOPS_ROOT_PATH,$matches[0][$i]);
				if (preg_match("/\.(".$GLOBALS['BlogCNF']['img_ext'].")$/i",$files[$i]['path'])) {
					$filename = cnv_mbstr(rawurldecode($files[$i]['path']));
					$dl_filename = preg_replace("/(\w+)_\d{1,14}_/","",$filename);
					$b = strrpos($filename,'/');
					$dl_filename = substr($dl_filename,$b+1);
				}else{
					$b = strrpos($files[$i]['path'],'/');
					$files[$i]['path'] = $GLOBALS['BlogCNF']['uploads'].substr($files[$i]['path'],$b);
					$filename = cnv_mbstr(rawurldecode($files[$i]['path']));
					$a = strpos($filename,'_');
					$b = strrpos($filename,'/');
					$c = strrpos($filename,'.');
					$dl_filename = substr($filename,$a+1,$c-$a-1);
				}
				$files[$i]['name']=$dl_filename;
			}
			$message = preg_replace("':download:'","",$message);
			$message = $myts->makeTareaData4Show(
				PopnupBlogUtils::_strcut($message,0,$GLOBALS['BlogCNF']['post_limit'])
			);
		}
		$message = $myts->stripSlashesGPC($message);
		$subj = $myts->stripSlashesGPC($subj);
		// Send to emailalias for mailinglist
		$sql = "SELECT email FROM ".POPNUPBLOG_TABLE_EMAIL_ALIAS." WHERE blogid = $blogid and public = 2";
		$r = $xoopsDB->query($sql);
		if ($GLOBALS['BlogCNF']['use_sitefrom']==1)
			$from = PopnupBlogUtils::getXoopsModuleConfig('MAILADDR');
		while( list($email) = $xoopsDB->fetchRow($r) ){
			 PopnupBlogUtils::send_mailinglist($from,$email,$uname,$subj,$blogname,$blogurl,$message,$files);
		}
		//
		// Send Notify for XOOPS event
		//
		PopnupBlogUtils::send_notify($blogid,$blogname,$blogurl,$subj,$message='');
	}
	function get_mailcode(){
		switch (_LANGCODE){
		case "af": $code = "ISO-8859-1";break;	//Afrikaans
		case "ar": $code = "ISO-8859-6";break;	//Arabic
		case "be": $code = "ISO-8859-5";break;	//Byelorussian
		case "bg": $code = "ISO-8859-5";break;	//Bulgarian
		case "ca": $code = "ISO-8859-1";break;	//Catalan
		case "cs": $code = "ISO-8859-2";break;	//Czech
		case "da": $code = "ISO-8859-1";break;	//Danish
		case "de": $code = "ISO-8859-1";break;	//German
		case "el": $code = "ISO-8859-7";break;	//Greek
		case "en": $code = "us-ascii";	break;	//English
		case "eo": $code = "ISO-8859-3";break;	//Esperanto
		case "es": $code = "ISO-8859-1";break;	//Spanish
		case "eu": $code = "ISO-8859-1";break;	//Basque
		case "et": $code = "iso-8859-15";break;	//Estonian
		case "fi": $code = "ISO-8859-1";break;	//Finnish
		case "fo": $code = "ISO-8859-1";break;	//Faroese
		case "fr": $code = "ISO-8859-1";break;	//French
		case "ga": $code = "ISO-8859-1";break;	//Irish
		case "gd": $code = "ISO-8859-1";break;	//Scottish
		case "gl": $code = "ISO-8859-1";break;	//Galician
		case "hr": $code = "ISO-8859-2";break;	//Croatian
		case "hu": $code = "ISO-8859-2";break;	//Hungarian
		case "is": $code = "ISO-8859-1";break;	//Icelandic
		case "it": $code = "ISO-8859-1";break;	//Italian
		case "iw": $code = "ISO-8859-8";break;	//Hebrew
		case "ja": $code = "ISO-2022-JP";break;	//Japanese (Shift_JIS)
		case "ko": $code = "EUC_KR";	break;	//Korean	
		case "lt": $code = "ISO-8859-13";break;	//Lithuanian
		case "lv": $code = "ISO-8859-13";break;	//Latvian
		case "mk": $code = "ISO-8859-5";break;	//Macedonian
		case "mt": $code = "ISO-8859-5";break;	//Maltese
		case "nl": $code = "ISO-8859-1";break;	//Dutch
		case "no": $code = "ISO-8859-1";break;	//Norwegian
		case "pl": $code = "ISO-8859-2";break;	//Polish
		case "pt": $code = "ISO-8859-1";break;	//Portuguese
		case "ro": $code = "ISO-8859-2";break;	//Romanian
		case "ru": $code = "ISO-8859-5";break;	//Russian
		case "sh": $code = "ISO-8859-5";break;	//Serbo-Croatian
		case "sk": $code = "ISO-8859-2";break;	//Slovak
		case "sl": $code = "ISO-8859-2";break;	//Slovenian
		case "sq": $code = "ISO-8859-2";break;	//Albanian
		case "sr": $code = "ISO-8859-2";break;	//Serbian
		case "sv": $code = "ISO-8859-1";break;	//Swedish
		case "th": $code = "TIS620";	break;	//Thai
		case "tr": $code = "ISO-8859-9";break;	//Turkish
		case "uk": $code = "ISO-8859-5";break;	//Ukrainian
		case "zh": $code = "GB2312";	break;	//Chainese	
		default: $code = "UTF-8";break;
		}
		return $code;
	}
}
function popnupblog_remove_html_tags_callback($t){
	return "";
}

?>
